﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

using System.Globalization;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.ServiceModel.Description;
using CRM.Tools.MetadataBrowser.CrmSdk;

namespace CRM.Tools.MetadataBrowser.Views
{
    public partial class EntityList : Page
    {

        public EntityList()
        {
            InitializeComponent();
         
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string serverUrl = ClientScript.GetServerUrl();
                     
            ExecuteRetrieveEntity(new Uri(serverUrl));

        }


        private void ExecuteRetrieveEntity(Uri ServerUrl)
        {

            try
            {
                OrganizationServiceClient client = (OrganizationServiceClient)WCFHelper.GetConnection(ServerUrl);
                
                OrganizationRequest request = new OrganizationRequest();
                request.RequestName = "RetrieveAllEntities";
                request.Parameters = new ParameterCollection();
                request.Parameters.Add(new CRM.Tools.MetadataBrowser.DataModel.KeyValuePair<string, object>("EntityFilters", EntityFilters.Entity));
                request.Parameters.Add(new CRM.Tools.MetadataBrowser.DataModel.KeyValuePair<string, object>("RetrieveAsIfPublished", false));
                client.ExecuteCompleted += new EventHandler<CrmSdk.ExecuteCompletedEventArgs>(ExecuteRetrieveEntities_ExecuteCompleted);

                client.ExecuteAsync(request);
            
            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                throw ex;
            }
        }

        private void ExecuteRetrieveEntities_ExecuteCompleted(object sender, CrmSdk.ExecuteCompletedEventArgs response)
        {
            try
            {
                ObservableCollection<EntityMetadata> data = (ObservableCollection<EntityMetadata>)response.Result.Results[0].Value;

                var entities = from a in data
                               orderby a.SchemaName
                               select a;

                // Bind to datagrdi
                uxData.ItemsSource = entities;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// Navigate to selected Entity Attributes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LogicalName_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!String.IsNullOrEmpty( ((HyperlinkButton)e.OriginalSource).Content.ToString()))
                {
                    //Uri link = new Uri(string.Format("/EntityAttributes/{0}", ((HyperlinkButton)e.OriginalSource).Content), UriKind.Relative);
                    Uri link = new Uri(string.Format("/EntityView/{0}", ((HyperlinkButton)e.OriginalSource).Content), UriKind.Relative);
                    NavigationService.Navigate(link);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void TreeView_Expanded(object sender, RoutedEventArgs e)
        {
          // ((TreeView)((TreeViewItem)sender).Parent).Height = double.NaN;
        }

        private void TreeView_Collapsed(object sender, RoutedEventArgs e)
        {
          // ((TreeView)((TreeViewItem)sender).Parent).Height = 50;
        }

        private void Export_Click(object sender, RoutedEventArgs e)
        {
            if (uxData.ItemsSource != null)
            {
                uxData.Export();
            }
            else
            {
                ChildWindow msg = new MessageWindow("No data to export");
                msg.Show();
            }
        }

      


     

    }
}
